#include "temp_password.h"
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>

/// 用来计算临时密码的hash code
/// 将字符串s转换成i32数值类型
/// 密码格式：AtguiguSmartLock001+8位时间戳

int32_t hash_code (char *s)
{
    int32_t hash = 0;
    int i = 0;
    while (i<19 +8) {
       hash = (hash << 5) - hash + ((uint8_t)s[i]|0);
       i++;
    }
    return hash;
}

uint8_t PASSWORD_ValidateTempPassword(uint8_t* input_password)
{
    time_t now;
    time(&now);
    uint64_t now_in_minutes = now / 60;
    now_in_minutes = now_in_minutes + 10;

    char buff[21];
    char* serial_number = "AtguiguSmartLock001";
    char key[27] = {0};

    for(int k = 0; k < 21; k++)
    {
        // copy to buffer
        sprintf(buff, "%" PRIu64, now_in_minutes-k);
        // printf("buff: %s\r\n", buff);

        
        for(int i = 0; i < 19; i++)
        {
            key[i] = serial_number[i];
        }

        for(int j = 19; j < 27; j++)
        {
            key[j] = buff[j-19];
        }
        int32_t hash = hash_code(key);
        // 生成6位数字密码(000000-999999)
        int32_t temp_password = abs(hash % 1000000);
        
        // 调试打印
        // printf("calculated temp_password: %06" PRId32 "\r\n", temp_password);

        // 转换为字符串
        char temp_password_str[7]; // 6位数 + null终止符
        snprintf(temp_password_str, sizeof(temp_password_str), "%06" PRId32, temp_password);
        
        // 比较密码
        if(strcmp((char *)input_password, temp_password_str) == 0) {
            return 1;
        }
    }
    return 0;
}